import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: () => import('@/views/Login/index.vue') },
  { path: '/reg', component: () => import('@/views/Reg/index.vue') },
  {
    path: '/',
    component: () => import('@/views/Layout/index.vue'),
    children: [
      { path: '/home', component: () => import('@/views/home/index.vue') },
      { path: '/user-info', component: () => import('@/views/user/userinfo') },
      {
        path: '/user-avatar',
        component: () => import('@/views/user/changeavatar')
      },
      { path: '/user-pwd', component: () => import('@/views/user/resetpwd') },
      {
        path: '/art-cate',
        component: () => import('@/views/art/artcategory')
      },
      { path: '/art-list', component: () => import('@/views/art/artlist') },
      { path: '/slot', component: () => import('@/views/slot/index.vue') },
      { path: '/father', component: () => import('@/views/father/index.vue') }
    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'hash'
})
/*
路由拦截：只要路由值发生改变就会触发
请求拦截：只要发送请求才会触发
 */
const whitelist = ['/login', '/reg']
router.beforeEach((to, from, next) => {
  console.log(to, from, 112233)
  /*
  判断：是否有token
  如果有token就直接放行，没有token说明未登录=》去登录
  */
  // if (to.path !== '/login') {
  if (!whitelist.includes(to.path)) {
    //  判断是不是有token
    if (store.state.token) {
      //  说明：已经登录
      next()
    } else {
      //  去的不是登录页面 又没有token  ===》去登陆
      next('/login')
    }
  } else {
    //  去的是登录页面
    next()
  }

  // next() //  放行
})

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

export default router
